from sanic import Sanic
from sanic.response import text
from sanic.response import json
import requests
import cv2
import base64
import time
import json as Json
import re
import difflib
import numpy as np
import os
from datetime import datetime
from sfz_ocr import sfz_ocr_predict
from sanic.log import logger
from paddleocr import PaddleOCR


app = Sanic("table-server")
ocr = PaddleOCR(use_pdserving=False, use_angle_cls=True, det=True, cls=True, lang='ch', show_log=False,
                cls_thresh=0.9, use_gpu=True, det_db_box_thresh=0.4, det_db_score_mode='slow',
                det_model_dir='./inference/yyzz_det_infer', 
                rec_model_dir='./inference/ch_PP-OCRv2_rec_infer', 
                cls_model_dir='./inference/ch_ppocr_mobile_v2.0_cls_infer')
app.config.setdefault('ocr', ocr)
# app.config.update(
#     {
#         "AUTO_RELOAD": False,
#         "ACCESS_LOG": False,
#     }
# )


def is_contain_chinese(check_str):
    """
    判断字符串中是否包含中文
    :param check_str: {str} 需要检测的字符串
    :return: {bool} 包含返回True， 不包含返回False
    """
    for ch in check_str:
        if u'\u4e00' <= ch <= u'\u9fff':
            return True
    return False


@app.post("/yyzz/predict")
async def hello_world(request):
    res = {
        'msg': 'ok',
        'code': 0,
        'data': {
            'code': '',
            'name': '',
            'type': '',
            'corp': '',
            'business': '',
            'address': '',
            'create_date': '',
            'in_date': '',
            'registered': '',
            'source_str_arr': []
        }
    }
    if len(request.files.keys()) != 1:
        res['msg'] = '必须传入一个图片'
        res['code'] = 1
        return json(res)
    f = request.files.get(list(request.files.keys())[0])
    input_img = cv2.imdecode(np.frombuffer(f.body, np.uint8), cv2.IMREAD_COLOR)
    res_ls = []
    try:
        result = app.config['ocr'].ocr(input_img)
        for line in result:
            res_ls.append(line[1][0])
    except Exception as e:
        logger.exception(e)
    res_dict = res['data']
    source_str_arr = []
    for item in res_ls:
        try:
            item  = item.replace(' ', '').replace('（1-1）', '').replace('(1-1)', '').replace('（1/1）', '').replace('(1/1)', '')
            if item in ('营业执照', '（副本）', '登记机关', '副本'):
                continue
            elif not res_dict['code'] and len(item) == 18 and not is_contain_chinese(item):
                res_dict['code'] = item
            elif not res_dict['code'] and '统一社会信用代码' in item and '统一社会信用代码' != item:
                res_dict['code'] = item.replace('统一社会信用代码', '')
            elif '名称' in item and '名称' != item:
                res_dict['name'] = item.replace('名称', '')
            elif '类型' in item and '类型' != item:
                res_dict['type'] = item.replace('类型', '')
            elif '法定代表人' in item and '法定代表人' != item:
                res_dict['corp'] = item.replace('法定代表人', '')
            elif '注册资本' in item and '注册资本' != item:
                res_dict['registered'] = item.replace('注册资本', '')
            elif '成立日期' in item and '成立日期' != item:
                res_dict['create_date'] = item.replace('成立日期', '')
            elif '注册日期' in item and '注册日期' != item:
                res_dict['create_date'] = item.replace('注册日期', '')
            elif '营业期限' in item and '营业期限' != item:
                res_dict['in_date'] = item.replace('营业期限', '')
            elif '住所' in item and '住所' != item:
                res_dict['address'] = item.replace('住所', '')
            elif '经营场所' in item and '经营场所' != item:
                res_dict['address'] = item.replace('经营场所', '')
            elif '营业场所' in item and '营业场所' != item:
                res_dict['address'] = item.replace('营业场所', '')
            elif '经营者' in item and '经营者' != item:
                res_dict['corp'] = item.replace('经营者', '')
            elif '负责人' in item and '负责人' != item:
                res_dict['corp'] = item.replace('负责人', '')
            elif '投资人' in item and '投资人' != item:
                res_dict['corp'] = item.replace('投资人', '')
        except Exception as e:
            logger.error(f'happen error {e}')
        finally:
            source_str_arr.append(item)
    res_dict['source_str_arr'] = source_str_arr
    res['data'] = res_dict
    return json(res)


if __name__ == "__main__":
    app.run(host='0.0.0.0', port='18083', debug=False, fast=True)